from django.http import JsonResponse
from django.middleware.csrf import get_token
from web.models import *
from web import utils
from django.forms.models import model_to_dict
from django.core.paginator import Paginator
from web.apis.module import Module
from django import forms
tools = utils.Utils()
module = Module()
# 返回CSRF Token
def get_csrf_token_view(request):
    csrf_token = get_token(request)
    response = JsonResponse({'CSRF': csrf_token})
    response.headers['CSRF'] = csrf_token
    return response


class SystemAnnouncementForm(forms.ModelForm):
    class Meta:
        model = SystemAnnouncement
        fields = ['title', 'content', 'user_id', 'is_pinned']

# 添加系统公告
def add_system_announcement(request):
    form = SystemAnnouncementForm(request.POST)
    if form.is_valid():
        form.save()
        announcement = model_to_dict(form.instance)
        announcement['create_time'] = tools.time_format(form.instance.create_time)
        announcement['update_time'] = tools.time_format(form.instance.update_time)
        return JsonResponse(tools.Response(code=200, message='添加成功', data=announcement))
    else:
        error = tools.Forms_GetError(form)
        return JsonResponse(tools.Response(code=400, message=f'{error[1]}', data=error[0]))


# 获取系统公告
def get_system_announcement(request):
    page = request.GET.get('page', 1)
    page_size = request.GET.get('page_size', 10)
    system_announcement = SystemAnnouncement.objects.all()
    paginator = Paginator(system_announcement, page_size)
    page_obj = paginator.page(page)
    data = []
    for item in page_obj.object_list:
        new_user_item = module.user_data_format(item.user_id)
        new_item = model_to_dict(item)
        new_item['create_time'] = tools.time_format(item.create_time)
        new_item['update_time'] = tools.time_format(item.update_time)
        new_item['username'] = new_user_item['username']
        # 把content截取前10个字符
        new_item['content'] = item.content[:10]
        data.append(new_item)
    result = {
        'count': paginator.count,
        'results': data,
        'page': page,
        'page_size': page_size
    }
    return JsonResponse(tools.Response(code=200, message='获取成功', data=result))


class SystemAnnouncementMediaForm(forms.ModelForm):
    class Meta:
        model = SystemAnnouncementMedia
        fields = ['system_announcement_id', 'media_url', 'media_type']

# 添加系统公告媒体资源
def add_system_announcement_media(request):
    form = SystemAnnouncementMediaForm(request.POST, files=request.FILES)
    if form.is_valid():
        form.save()
        return JsonResponse(tools.Response(code=200, message='添加成功'))
    else:
        error = tools.Forms_GetError(form)
        return JsonResponse(tools.Response(code=400, message=f'{error[1]}', data=error[0]))

# 获取公告栏详情
def get_system_announcement_detail(request):    
    system_announcement_id = request.GET.get('system_announcement_id')
    system_announcement = SystemAnnouncement.objects.filter(id=system_announcement_id).first()
    if not system_announcement:
        return JsonResponse(tools.Response(code=400, message='公告不存在'))
    system_announcement_media = SystemAnnouncementMedia.objects.filter(system_announcement_id=system_announcement_id)
    media_data = []
    for item in system_announcement_media:
        new_item = model_to_dict(item)
        new_item['media_url'] = item.media_url.url
        new_item['media_type'] = item.get_media_type_display()
        media_data.append(new_item)
    new_system_announcement = model_to_dict(system_announcement)
    new_system_announcement['media_data'] = media_data
    new_system_announcement['create_time'] = tools.time_format(system_announcement.create_time)
    new_system_announcement['update_time'] = tools.time_format(system_announcement.update_time)
    return JsonResponse(tools.Response(code=200, message='获取成功', data=new_system_announcement))


class SystemVersionForm(forms.ModelForm):
    class Meta:
        model = SystemVersion
        fields = ['version', 'download_url']

# 添加系统版本
def add_system_version(request):
    form = SystemVersionForm(request.POST)
    if form.is_valid():
        form.save()
        version = model_to_dict(form.instance)
        version['create_time'] = tools.time_format(form.instance.create_time)
        version['update_time'] = tools.time_format(form.instance.update_time)
        return JsonResponse(tools.Response(code=200, message='添加成功', data=version))
    else:
        error = tools.Forms_GetError(form)
        return JsonResponse(tools.Response(code=400, message=f'{error[1]}', data=error[0]))

# 获取系统版本
def get_system_version(request):
    system_version = SystemVersion.objects.all().order_by('-create_time')
    data = []
    for item in system_version:
        new_item = model_to_dict(item)
        new_item['create_time'] = tools.time_format(item.create_time)
        new_item['update_time'] = tools.time_format(item.update_time)

        system_version_update = SystemVersionUpdate.objects.filter(system_version_id=item.id)
        
        update_data = []
        for update_item in system_version_update:
            new_update_item = model_to_dict(update_item)
            new_update_item['update_type'] = update_item.get_update_type_display()
            update_data.append(new_update_item)
        new_item['update_data'] = update_data
        data.append(new_item)
    return JsonResponse(tools.Response(code=200, message='获取成功', data=data))


class SystemVersionUpdateForm(forms.ModelForm):
    class Meta:
        model = SystemVersionUpdate
        fields = ['system_version_id', 'update_type', 'update_content']

# 添加系统版本更新
def add_system_version_update(request):
    form = SystemVersionUpdateForm(request.POST)
    if form.is_valid():
        form.save()
        return JsonResponse(tools.Response(code=200, message='添加成功'))
    else:
        error = tools.Forms_GetError(form)
        return JsonResponse(tools.Response(code=400, message=f'{error[1]}', data=error[0]))


class SystemNotificationForm(forms.ModelForm):
    class Meta:
        model = SystemNotification
        fields = ['user_id', 'content']

# 添加系统通知
def add_system_notification(request):
    form = SystemNotificationForm(request.POST)
    if form.is_valid():
        form.save()
        return JsonResponse(tools.Response(code=200, message='添加成功'))
    else:
        error = tools.Forms_GetError(form)
        return JsonResponse(tools.Response(code=400, message=f'{error[1]}', data=error[0]))

# 获取系统通知
def get_system_notification(request):
    user_id = request.GET.get('user_id')
    system_notification = SystemNotification.objects.filter(user_id=user_id).order_by('-create_time')
    data = []
    for item in system_notification:
        new_item = model_to_dict(item)
        new_item['create_time'] = tools.time_format(item.create_time)
        new_item['update_time'] = tools.time_format(item.update_time)
        # 内容截取前30个字符
        new_item['content'] = item.content[:30] + "..."
        data.append(new_item)
    return JsonResponse(tools.Response(code=200, message='获取成功', data=data))

# 更新系统通知
def update_system_notification(request):
    system_notification_id = request.GET.get('system_notification_id')
    system_notification = SystemNotification.objects.filter(id=system_notification_id).first()
    if not system_notification:
        return JsonResponse(tools.Response(code=400, message='通知不存在'))
    if system_notification.is_read == True:
        return JsonResponse(tools.Response(code=400, message='通知已读'))
    system_notification.is_read = True
    system_notification.save()
    return JsonResponse(tools.Response(code=200, message='更新成功'))

# 获取系统通知的详情
def get_system_notification_detail(request):
    system_notification_id = request.GET.get('system_notification_id')
    system_notification = SystemNotification.objects.filter(id=system_notification_id).first()
    if not system_notification:
        return JsonResponse(tools.Response(code=400, message='通知不存在'))
    
    # 判断是否已读
    if system_notification.is_read == False:
        system_notification.is_read = True
        system_notification.save()

    new_system_notification = model_to_dict(system_notification)
    new_system_notification['user'] = module.user_data_format(system_notification.user_id)
    del new_system_notification['user']['account']
    del new_system_notification['user_id']
    new_system_notification['create_time'] = tools.time_format(system_notification.create_time)
    new_system_notification['update_time'] = tools.time_format(system_notification.update_time)
    return JsonResponse(tools.Response(code=200, message='获取成功', data=new_system_notification))


class ContactUsForm(forms.ModelForm):
    class Meta:
        model = ContactUs
        fields = ['contact_way', 'contact_content', 'contact_qr']

# 创建联系我们
def create_contact_us(request):
    form = ContactUsForm(request.POST, files=request.FILES)
    if form.is_valid():
        form.save()
        return JsonResponse(tools.Response(code=200, message='添加成功'))
    else:
        error = tools.Forms_GetError(form)
        return JsonResponse(tools.Response(code=400, message=f'{error[1]}', data=error[0]))

# 获取联系我们
def get_contact_us(request):
    contact_us = ContactUs.objects.all()
    data = []   
    for item in contact_us:
        new_item = model_to_dict(item)
        new_item['create_time'] = tools.time_format(item.create_time)
        new_item['update_time'] = tools.time_format(item.update_time)
        new_item['contact_qr'] = item.contact_qr.url
        data.append(new_item)
    return JsonResponse(tools.Response(code=200, message='获取成功', data=data))


# 删除联系我们
def delete_contact_us(request):
    contact_us_id = request.GET.get('contact_us_id')
    contact_us = ContactUs.objects.filter(id=contact_us_id).first()
    if not contact_us:
        return JsonResponse(tools.Response(code=400, message='联系我们不存在'))
    contact_us.delete()
    return JsonResponse(tools.Response(code=200, message='删除成功'))
